package com.cmbchina.service;

import com.cmbchina.entity.Currency;
import com.cmbchina.entity.ExchangeRate;
import com.cmbchina.entity.Money;
import com.cmbchina.entity.SinaExchangeRate;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 支付案例
 */
public class PayService {

    @Autowired
    private BankService bankService;

    /**
     * 跨境支付
     * @param money
     * @param recipientId
     */
    public void pay(Money money, Currency targetCurrency, Long recipientId){
        //1、从新浪网站获取新浪格式汇率
        SinaExchangeRate sinaRate = getSinaExchangeRate(money.getCurrency(), targetCurrency);
        //2、将新浪汇率格式转换为当前系统的汇率格式
        ExchangeRate rate = convertExhangeRate(sinaRate);
        //3、根据汇率转换金额
        Money targetMoney = rate.exchange(money);
        //4、转账
        bankService.tranfer(targetMoney, recipientId);
    }

    /**
     * 将新浪汇率格式转换当前系统汇率格式
     * @param sinaRate
     * @return
     */
    private ExchangeRate convertExhangeRate(SinaExchangeRate sinaRate){
        if(Objects.isNull(sinaRate)){
            throw new IllegalArgumentException("汇率不能为null");
        }
        Currency sourceCurrency = sinaRate.getSourceCurrency();
        Currency targetCurrency = sinaRate.getTargetCurrency();
        sinaRate.getRate();
        //格式转换
        BigDecimal rate = new BigDecimal(sinaRate.getRate());
        return new ExchangeRate(rate, sourceCurrency, targetCurrency);
    }

    /**
     * 从新浪网站获取汇率
     * @param from
     * @param to
     * @return
     */
    private SinaExchangeRate getSinaExchangeRate(Currency from, Currency to){
        return new SinaExchangeRate("1.4", from, to);
    }
}
